<template>
  <div class="intent mbm">
    <h4 class="step_title mbm">第三步，来电意图和闲聊处理：</h4>
    <a-tabs type="card">
      <a-tab-pane tab="3.1 来电意图分类" key="1">
        <div class="mbm">
          <a-button type="primary" @click="showModalSid({},0,$event)">
            <a-icon type="folder-add" />新增分类
          </a-button>
        </div>
        <a-row :gutter="16">
          <a-col :span="24/rows" class="mbm" v-for="(cv,ck) in cards" :key="ck">
            <div
              :class="classCardBox(ck,cards.length)"
              @mouseover="actionTop($event,true)"
              @mouseout="actionTop($event,false)"
            >
              <a-card>
               
                <a @click="showModalSid(cv,ck,$event)" slot="extra">
                   <a-tooltip :title="'挂断语音：'+cv.policy.title"><a-icon type="setting" />设置</a-tooltip>
                </a>
                
              <div class="title" slot="title">{{cv.title}}</div>
                
                <div class="queries">
                  <a-row :gutter="10">
                    <a-col :lg="24" :xl="12" v-for="(iv,ik) in cv.queries" :key="ik">
                      <a class="mrs" @click="showModalQuery(iv,ik,cv,ck,$event)">{{stringOr(iv.query)}}</a>
                      <span class="answer">{{stringOr(iv.answer)}}</span>
                    </a-col>
                  </a-row>
                </div>
                <div class="add_query_btn">
                  <a @click="showModalQuery({},0,cv,ck,$event)">+新增关键词匹配</a>
                </div>
              </a-card>
            </div>
          </a-col>
        </a-row>
      </a-tab-pane>
      <a-tab-pane tab="3.2 闲聊处理" key="2">
        <div class="queries">
          <a-row :gutter="16">
            <a-col
              class="mbm"
              :xs="24"
              :sm="12"
              :md="6"
              :lg="4"
              :xl="4"
              v-for="(hv,hk) in hello.queries"
              :key="hk"
            >
              <a class="mrs" @click="showModalQuery(hv,hk,hello,0,$event)">{{stringOr(hv.query)}}</a>
              <span class="answer">{{stringOr(hv.answer)}}</span>
            </a-col>
          </a-row>
        </div>
        <div class="add_query_btn mbm">
          <a @click="showModalQuery({},0,hello,0,$event)">+新增关键词匹配</a>
        </div>
      </a-tab-pane>
    </a-tabs>
    <a-modal
      :title="modalSidTitle"
      :visible="visibleSid"
      :confirmLoading="loadingSid"
      @ok="submitSid"
      @cancel="cancelSid"
      :footer="null"
      :mask="true"
      :maskClosable="false"
    >
      <a-form :form="formSid" @submit="submitSid">
        <a-form-item
          label="分类名称"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
          extra="建议按照行业分类命名"
        >
          <a-input
            class="talk_input mrm"
            style="width: 120px"
            placeholder="如：“房屋中介”，“贷款”。"
            v-decorator="['title',{ rules: [{ required: true, message: '必须输入分类名称！' }] }]"
          />
        </a-form-item>
        <a-form-item
          label="挂断策略"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 19 }"
          extra="可以选择已有的策略，或者直接输入要说的话。"
        >
          <a-select
            showSearch
            placeholder="请选择策略，或者输入要说的话"
            optionFilterProp="children"
            style="width: 270px;margin-right:10px"
            @focus="sidFocus"
            @blur="sidBlur"
            @change="sidChange"
            :filterOption="sidOption"
            v-decorator="['end',{ rules: [] }]"
          >
            <a-select-option v-for="(v,k) in modalSidPolicy" :key="k" :value="v.id">[策略] {{v.title}}</a-select-option>
          </a-select>
          <router-link to="/settings/end">管理策略</router-link>
        </a-form-item>
        <a-form-item
          label="优先级排序"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"          
        >
        <div slot="extra">如果一通电话同时涉及了多个分类，则以优先级值最高的为最终分类结果。<a title="查看更多帮助" target="_blank" :href="this.$api.help.url.intent"><a-icon type="question-circle" /></a></div>
          <a-input
            class="talk_input mrm"
            style="width: 90px"
            placeholder="如：“50”"
            v-decorator="['level',{ rules: [{ type: `number`,transform: Number, message: '必须是数字哦！' }] }]"
          />
        </a-form-item>
        <a-form-item v-if="editSid.vSid" :wrapper-col="{ span: 12, offset: 5 }">
          <a-button class="mbm mrm" @click="removeSid(editSid)">删除</a-button>
          <a-button class="mbm" type="primary" html-type="submit">立即修改</a-button>
        </a-form-item>
        <a-form-item v-else :wrapper-col="{ span: 12, offset: 5 }">
          <a-button class="mbm" type="primary" html-type="submit">立即新增</a-button>
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal
      :title="modalQueryTitle"
      :visible="visibleQuery"
      :confirmLoading="loadingQuery"
      @ok="submitQuery"
      @cancel="cancelQuery"
      :footer="null"
      :mask="true"
      :maskClosable="false"
    >
      <a-form :form="formQuery" class="form_query" @submit="submitQuery">
        <a-form-item          
          label="关键词匹配"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
          extra="请输入一个尽量简短的中文词"
          class="item_query"
        >
          <a-select v-if="editQuery.vMode==1"
            mode="tags"
            :tokenSeparators="['|','｜',',','，']"
            class="talk_input mrm"
            style="width: 230px"
            placeholder="如：“出租”，可用“|”间隔多个。"
            v-decorator="['query_kw',{initialValue:editQuery.vQueryKW, rules: [{ required: true, message: '必须输入一个中文关键词！' }] }]"
          ></a-select>       
          <a-textarea v-else 
            class="talk_input mrm"
            style="width: 230px"
            placeholder="如：“(出租*)”，当前可使用正则表达式。"
            v-decorator="['query_re',{ initialValue:editQuery.vQueryRE,rules: [{ required: true, message: '必须输入一个中文关键词！' }] }]"
          ></a-textarea>
          <a-checkbox class="check_regexp" :checked="editQuery.vMode==2" @change="onRegexp">正则？</a-checkbox>
        </a-form-item>

        <a-form-item
          label="应答话术"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 16 }"
          extra="关键词匹配成功之后的应答语音，为空则沉默。"
        >
          <a-select
            mode="tags"
            :tokenSeparators="['|','｜']"
            class="talk_input mrm"
            style="width: 300px"
            placeholder="如：“不需要，谢谢”，可用“|”间隔多个。"
            v-decorator="['answer',{ initialValue:editQuery.vAnswer,rules: [] }]"
          ></a-select>
        </a-form-item>
        <a-form-item
          label="权重分"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"          
        >
        <div slot="extra">匹配成功的多个关键词的“权重分”相加之和达到100分，则自动触发“挂断策略”。<a title="查看更多帮助" target="_blank" :href="this.$api.help.url.intent"><a-icon type="question-circle" /></a></div>
          <a-input
            class="talk_input mrm"
            style="width: 90px"
            placeholder="如：“50”"
            v-decorator="['scores',{ initialValue:editQuery.vScores,rules: [{ type: 'number',transform: Number, message: '必须是数字哦！' }] }]"
          />
        </a-form-item>
        <a-form-item v-if="editQuery.vId" :wrapper-col="{ span: 12, offset: 5 }">
          <a-button class="mbm mrm" @click="removeQuery(editQuery)">删除</a-button>
          <a-button class="mbm" type="primary" html-type="submit">立即修改</a-button>
        </a-form-item>
        <a-form-item v-else :wrapper-col="{ span: 12, offset: 5 }">
          <a-button class="mbm" type="primary" html-type="submit">立即新增</a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script>
export default {
  data() {
    const intention = {
      vKey: 0,
      vSid: 0,
      vLevel: 0,
      vTitle: "",
      vEnd: ""
    };
    const query = {
      vKey: 0,
      vId: 0,
      vSid: 0,
      vScores: 0,
      vQueryKW: [],
      vQueryRE: "",
      vAnswer: [],
      vHello: false,
      vMode: 0
    };
    return {
      rows: 4,
      formQuery: this.$form.createForm(this, { name: "form_query" }),
      formSid: this.$form.createForm(this, { name: "form_sid" }),
      visibleQuery: false,
      loadingQuery: false,
      modalQueryTitle: "",
      editQuery: query,
      visibleSid: false,
      loadingSid: false,
      modalSidTitle: "",
      modalSidPolicy: [],
      editSid: intention,
      cards: [],
      hello: { title: "闲聊", queries: [],policy:{}},
      sidTitle: ["来电意图分类", "闲聊处理"]
    };
  },
  computed: {
    formCheck() {
      if (this.cards.length > 0 && this.cards[0].queries.length > 0) {
        return 0;
      } else {
        return 1;
      }
    }
  },
  mounted: function() {
    this.loadIntention();
  },
  methods: {
    newSid(v, i) {
      return {
        key: i,
        title: v.title,
        queries: v.queries,
        policy: v.policy,
        sid: v.sid,
        level: v.level,
        end: v.end
      };
    },
    newQuery(v) {
      return {
        id: v.id,
        sid: v.sid,
        query: v.query,
        answer: v.answer,
        scores: v.scores,
        mode: v.mode
      };
    },
    stringOr(v){
      return v.split(",").join("|")
    },
    loadIntention() {
      this.$api.talk
        .getIntentionList()
        .then(ilist => {
          var intentions = [];
          ilist.forEach((v, i) => {
            if (v.hello) {
              this.hello = v;
            } else {
              intentions.push(this.newSid(v, i));
            }
          });
          intentions.sort(function(a, b) {
            return b.level - a.level;
          });
          this.cards = intentions;
        })
        .catch(err => {
          console.log(err);
        });
    },
    loadPolicy() {
      this.$api.setting
        .getPolicyList()
        .then(res => {
          this.modalSidPolicy = [];
          res.forEach(v => {
            this.modalSidPolicy.push({ id: v.id.toString(), title: v.title });
          });
        })
        .catch(err => {
          console.log(err);
        });
    },
    showModalSid(v, k) {
      this.visibleSid = true;
      this.editSid.vKey = k;
      if (typeof v.sid != "undefined") {
        this.modalSidTitle = "修改-" + this.sidTitle[0];
        this.editSid.vSid = v.sid;
        this.editSid.vTitle = v.title;
        this.editSid.vEnd = v.end;
        this.editSid.vLevel = v.level;
      } else {
        this.modalSidTitle = "新增-" + this.sidTitle[0];
        this.editSid.vSid = 0;
        this.editSid.vTitle = "";
        this.editSid.vEnd = "";
        this.editSid.vLevel = 0;
      }
      this.loadPolicy();
      this.$nextTick(function() {
        this.formSid.setFieldsValue({
          title: this.editSid.vTitle,
          end: this.editSid.vEnd,
          level: this.editSid.vLevel
        });
      });
    },
    cancelSid() {
      this.visibleSid = false;
    },
    showModalQuery(v, k, cv, ck) {
      this.visibleQuery = true;
      this.editQuery.vKey = ck;
      this.editQuery.vSid = cv.sid;
      this.editQuery.vHello = cv.hello;

      if (typeof v.id != "undefined") {
        this.modalQueryTitle = "修改-" + cv.title;
        this.editQuery.vId = v.id;
        this.editQuery.vScores = v.scores;
        this.editQuery.vQueryKW = v.query ? v.query.split(",") : [];
        this.editQuery.vQueryRE = v.query ? v.query.toString() : "";
        this.editQuery.vAnswer = v.answer ? v.answer.split(",") : [];
        this.editQuery.vMode = v.mode;
      } else {
        this.modalQueryTitle = "新增-" + cv.title;
        this.editQuery.vId = 0;       
        this.editQuery.vScores = cv.hello ?0:30;
        this.editQuery.vQueryKW = [];
        this.editQuery.vQueryRE = "";
        this.editQuery.vAnswer = [];
        this.editQuery.vMode = 1;
      }

      /* this.$nextTick(function() {
        this.formQuery.setFieldsValue({
          query_kw: this.editQuery.vQueryKW,
          query_re: this.editQuery.vQueryRE,
          answer: this.editQuery.vAnswer,
          scores: this.editQuery.vScores
        });
      }); */
    },
    cancelQuery() {
      this.visibleQuery = false;
      if (this.editQuery.vId > 0) {
        this.$nextTick(function() {
          this.formQuery.resetFields();
        });
      }
    },
    sidChange() {
      //console.log(`selected ${value}`);
    },
    sidBlur() {
      //console.log("blur");
    },
    sidFocus() {
      //console.log("focus");
    },
    sidOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    onRegexp() {
      this.editQuery.vQueryKW = this.formQuery.getFieldValue("query_kw")
      this.editQuery.vQueryRE = this.formQuery.getFieldValue("query_re")

      this.editQuery.vMode = this.editQuery.vMode == 2 ? 1 : 2;      
      if (this.editQuery.vMode == 1) {
        this.editQuery.vQueryKW = this.editQuery.vQueryRE
          ? this.editQuery.vQueryRE.split(",")
          : [];
      } else {
        this.editQuery.vQueryRE = this.editQuery.vQueryKW
          ? this.editQuery.vQueryKW.toString()
          : "";
      }
    },
    submitQuery(e) {
      e.preventDefault();
      this.formQuery.validateFields((err, values) => {
        if (!err) {
          let _id = this.editQuery.vId;
          let _sid = this.editQuery.vSid;
          let _key = this.editQuery.vKey;
          let _hello = this.editQuery.vHello;
          let _mode = this.editQuery.vMode;
          let _query;
          if (_mode == 1) {
            _query = values.query_kw;
          } else {
            _query = values.query_re;
          }
          this.$api.talk
            .addOrUpdateQuery({
              id: _id ? parseInt(_id) : 0,
              sid: _sid ? parseInt(_sid) : 0,
              query: _query,
              answer: values.answer == "undefined" ?"": values.answer,
              scores: values.scores ? parseInt(values.scores) : 0,
              mode: _mode ? parseInt(_mode) : 0
            })
            .then(res => {
              this.editQuery.vId = res.id;
              if (_hello) {
                if (_id > 0) {
                  this.hello.queries.forEach((ev, ek) => {
                    if (_id == ev.id) this.hello.queries.splice(ek, 1);
                  });
                }
                this.hello.queries.push(this.newQuery(res));
                this.hello.queries.sort(function(a, b) {
                  return b.scores - a.scores;
                });
              } else {
                if (_id > 0) {
                  this.cards[_key].queries.forEach((ev, ek) => {
                    if (_id == ev.id) this.cards[_key].queries.splice(ek, 1);
                  });
                }
                this.cards[_key].queries.push(this.newQuery(res));
                this.cards[_key].queries.sort(function(a, b) {
                  return b.scores - a.scores;
                });
              }
              this.$nextTick(function() {
                this.formQuery.resetFields();
              });
              this.visibleQuery = false;
            })
            .catch(err => {
              console.log(err);
            });
        }
      });
    },
    submitSid(e) {
      e.preventDefault();
      this.formSid.validateFields((err, values) => {
        if (!err) {
          var _sid = this.editSid.vSid;
          var _key = this.editSid.vKey;
          this.$api.talk
            .addOrUpdateIntention({
              sid: _sid ? parseInt(_sid) : 0,
              title: values.title,
              end: values.end,
              level: parseInt(values.level)
            })
            .then(res => {
              this.editSid.vSid = res.sid;
              let modalSidPolicyTitle = this.modalSidPolicy.find(function (obj) {
                return obj.id === res.end
              })
              res.policy = modalSidPolicyTitle?modalSidPolicyTitle:{id:"",title:values.end};
              if (_sid > 0) {
                res.queries = this.cards[_key].queries;
                this.cards[_key] = this.newSid(res, _key);
              } else {
                this.cards.push(this.newSid(res, this.cards.length));
              }
              this.cards.sort(function(a, b) {
                return b.level - a.level;
              });

              this.visibleSid = false;
            })
            .catch(err => {
              console.log(err);
            });
        }
      });
    },
    removeSid(edit) {
      var _that = this;
      this.$confirm({
        title: "您确认要删除分类 [ " + edit.vTitle + " ] 吗?",
        content: "注意，删除操作将不可恢复。",
        okType: "danger",
        onOk() {
          _that.$api.talk
            .delIntention({
              sid: edit.vSid ? parseInt(edit.vSid) : 0
            })
            .then(() => {
              _that.cards.splice(edit.vKey, 1);
              _that.visibleSid = false;
            })
            .catch(err => {
              console.log(err);
            });
        },
        onCancel() {}
      });
    },
    removeQuery(edit) {
      var _that = this;
      let _query;
      if (edit.vMode == 1) {
            _query = edit.vQueryKW;
          } else {
            _query = edit.vQueryRE;
          }
      this.$confirm({
        title: "您确认要删除关键词 [ " + _query.toString() + " ] 吗?",
        content: "注意，删除操作将不可恢复。",
        okType: "danger",
        onOk() {
          _that.$api.talk
            .delQuery({
              id: edit.vId ? parseInt(edit.vId) : 0
            })
            .then(() => {
              if (edit.vHello) {
                _that.hello.queries.forEach((ev, ek) => {
                  if (edit.vId == ev.id) _that.hello.queries.splice(ek, 1);
                });
              } else {
                _that.cards[edit.vKey].queries.forEach((ev, ek) => {
                  if (edit.vId == ev.id)
                    _that.cards[edit.vKey].queries.splice(ek, 1);
                });
              }
              _that.$nextTick(function() {
                _that.formQuery.resetFields();
              });
              _that.visibleQuery = false;
            })
            .catch(err => {
              console.log(err);
            });
        },
        onCancel() {}
      });
    },
    //最底部的card不需要折叠
    classCardBox(k, num) {
      let y = num % this.rows;
      let last = num - (y == 0 ? this.rows : y);
      if (k + 1 > last) {
        return "";
      } else {
        return "card_box";
      }
    },
    actionTop(e, over) {
      if (e.currentTarget.className.indexOf("card_box") != -1) {
        if (over) {
          e.currentTarget.className = "card_box action";
        } else {
          e.currentTarget.className = "card_box ";
        }
      }
    }
  }
};
</script>
<style lang="less" scoped>
.intent {
  .card_box {
    width: 100%;
    min-height: 280px;
    position: relative;
    z-index: 1;
    transition: z-index 0.5s ease;
    .ant-card {
      position: absolute;
      width: 100%;
    }
    .queries {
      max-height: 105px;
      overflow: hidden;
      overflow-y: auto;
      transition: max-height 0.5s ease;
    }
    &.action {
      z-index: 999;
      .queries {
        max-height: 400px;
      }
    }
  }

  .answer {
    font-size: 12px;
    color: #b9b9b9;
  }

  .add_query_btn {
    clear: both;
    padding-top: 16px;
  }
  .card_bottom {
    text-align: right;
    margin-bottom: 0;
  }
}
.form_query {
  .item_query {
    position: relative;
  }
  .check_regexp {
    position: absolute;
    right: -90px;
  }
}
</style>